/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { connect, useHistory, useLocation } from "dva";

import { Button, Row, Collapse, Modal, Col, message } from "antd";

import isArray from "lodash/isArray";
import numeral from "numeral";
import StandardTable from "@/components/StandardTable";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import { brandsMap_name } from "@/utils/utils";
import citys from "@kb/citys";
import Area from "./components/Area";
import styles from "./index.less";

const { Panel } = Collapse;

const formatCitys = citys[1].filter(item => item);

// 格式化数字显示
const formatNumber = (val, unit, emptyText = "--") => {
  const numFormat = "0.00";
  return val ? (
    <span>
      {numeral(val).format(numFormat)}
      {unit}
    </span>
  ) : (
    emptyText
  );
};

const Detail = props => {
  const { submitting, dispatch } = props;

  const { id } = useLocation().query || {};
  const history = useHistory();
  // 基本信息
  const [base, updateInfo] = useState(null);
  // 报价区域
  const [areas, updateArea] = useState(null);
  // 已选中的区域
  const [selectted, updateSelectted] = useState([]);
  const [editAreaData, updateEditAreaData] = useState(null);
  // 获取详情信息
  const getDetail = ids => {
    if (dispatch) {
      dispatch({
        type: "order_finance/getQuotationDetail",
        payload: {
          id: ids,
        },
      }).then(res => {
        const { code, data } = res;
        if (code == 0 && data) {
          const { areas: areass, ...rest } = data;
          updateInfo(rest);
          updateArea(
            areass.map(({ provices, ...rests }) => ({
              ...rests,
              provices: provices
                .split("、")
                .map(item => formatCitys.find(itemm => itemm.name == item))
                .map(({ id: ides, name }) => ({ id: ides, name })),
            }))
          );
        }
      });
    }
  };

  useEffect(() => {
    if (id) {
      getDetail(id);
      return;
    }
    // 新增报价单时存在临时数据
    const TempData = props.order_finance.qouteTemp;
    if (!TempData) {
      history.go(-1);
    } else {
      updateInfo(TempData);
    }
  }, []);

  // 区域变化，重新设置选中的城市
  useEffect(
    () => {
      const provinces = [];
      if (areas) {
        const list = isArray(areas) ? areas : [areas];
        list.map(item => {
          provinces.push(...(item.provices || []));
        });
      }
      updateSelectted(provinces);
    },
    [areas]
  );

  // 区域报价列配置项
  const columnsArea = useMemo(
    () => [
      {
        title: "发往地区",
        dataIndex: "provices",
        key: "provices",
        align: "center",
        width: "20%",
        render: val => val && val.map(item => item.name).join("，"),
      },
      {
        title: "首重",
        dataIndex: "f_kg",
        key: "f_kg",
        align: "center",
        render: val => formatNumber(val, "kg"),
      },
      {
        title: "首重价格",
        dataIndex: "f_weight",
        key: "f_weight",
        align: "center",
        render: val => formatNumber(val, "元"),
      },
      {
        title: "续重价格",
        dataIndex: "renewal_price",
        key: "price_renewal",
        align: "center",
        render: (_, item) => {
          return (
            <div>
              {formatNumber(item.s_weight, "元")} / {formatNumber(item.s_kg, "kg")}
            </div>
          );
        },
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "operator",
        align: "center",
        render: (_, item) => (
          <div>
            <a onClick={handleEdit.bind(null, item)}>编辑</a>
            <a
              style={{ marginLeft: "20px", color: "red" }}
              onClick={handleDelete.bind(null, item.id)}
            >
              删除
            </a>
          </div>
        ),
      },
    ],
    [areas]
  );

  // // 删除区域报价
  const handleDelete = useCallback(
    ids => {
      Modal.confirm({
        title: "温馨提示",
        centered: true,
        content: "确定要删除该条区域报价单吗？",
        cancelText: "取消",
        okText: "确定",
        onOk: () => {
          const area_ = [...areas];
          const index = area_.findIndex(item => item.id === ids);
          area_.splice(index, 1);
          updateArea(area_);
        },
      });
    },
    [areas]
  );

  // 编辑区域报价
  const handleEdit = item => {
    updateEditAreaData(item);
  };
  // 关闭区域报价弹窗
  const handleCloseAreaAdd = useCallback(() => {
    updateEditAreaData(null);
  }, []);
  // 新增区域报价
  const handleAreaChange = useCallback(
    data => {
      const area_ = [...(areas || [])];
      const index = area_.findIndex(item => item.id === data.id);
      if (index >= 0) {
        area_.splice(index, 1, {
          // ...area_[index],
          ...data,
        });
        updateArea(area_);
      } else {
        updateArea([data, ...area_]);
      }
    },
    [areas]
  );

  // 提交报价单
  const handleSubmit = useCallback(
    () => {
      dispatch({
        type: "order_finance/quotationSave",
        payload: {
          id: id || "",
          ...base,
          areas: JSON.stringify(
            areas.map(({ provices, id: ids, ...rest }) => ({
              ...rest,
              provices: provices.map(item => item.name).join("、"),
            }))
          ),
        },
      }).then(() => {
        message.success("操作成功", 1);
        history.go(-1);
      });
    },
    [id, areas, base]
  );

  return (
    <PageHeaderLayout title="编辑报价单">
      <div className={styles.main}>
        <div className={styles.detail}>
          <Collapse defaultActiveKey="base">
            <Panel header={<div className={styles.titleb}>基本信息</div>} key="base">
              <Row className={styles.titleb_row}>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.titleb_row_col}>
                      报价单名称
                    </Col>
                    <Col span={16}>{base?.name}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.titleb_row_col}>
                      品牌
                    </Col>
                    <Col span={16}>{brandsMap_name(base?.brand)}</Col>
                  </Row>
                </Col>
              </Row>
              <Row className={styles.titleb_row}>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.titleb_row_col}>
                      报价单模式
                    </Col>
                    <Col span={16}>首重/续重</Col>
                  </Row>
                </Col>
              </Row>
            </Panel>
          </Collapse>

          <Row className={styles.title}>
            <span className={styles.titleb}>区域报价</span>
            <Area
              data={editAreaData}
              onClose={handleCloseAreaAdd}
              selectted={selectted}
              onChange={handleAreaChange}
            />
          </Row>

          <StandardTable
            rowKey={record => record.id}
            columns={columnsArea}
            data={{ list: areas }}
            scroll={{ x: 1200 }}
            locale={{ emptyText: "暂未配置" }}
          />
          <div className={styles.btnbox}>
            <Button
              type="primary"
              className="kb-btn-long"
              onClick={handleSubmit}
              loading={submitting}
              size="large"
              disabled={!areas || areas.length == 0}
            >
              确认并提交
            </Button>
          </div>
        </div>
      </div>
    </PageHeaderLayout>
  );
};

Detail.defaultProps = {};

export default connect(({ order_finance, loading }) => ({
  getting: loading.effects["order_finance/getQuotationDetail"],
  submitting: loading.effects["order_finance/quotationSave"],
  order_finance,
}))(Detail);
